import { getCurrentToken } from './auth'
import { getApiUrl } from './config'
import type { 
  UploadFormData, 
  FileInfo, 
  UploadedFile, 
  UploadOptions,
  BusinessType,
  AttachmentType 
} from '../types/upload'

/**
 * 格式化文件大小
 * @param bytes 文件大小（字节）
 * @returns 格式化后的文件大小字符串（如 1.5 KB）
 */
export const formatFileSize = (bytes: number): string => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}



/**
 * 上传单个文件
 * @param options 上传选项
 * @returns Promise<string> 返回上传后的文件URL
 */
export const uploadFile = (options: UploadOptions): Promise<string> => {
  const { url, file, formData = {}, onProgress } = options

  return new Promise<string>((resolve, reject) => {
    const uploadTask = uni.uploadFile({
      url,
      filePath: file.path,
      name: 'file',
      header: {
        'Token': getCurrentToken()
      },
      formData: {      
        ...formData,
        'file_name': file.name,
        'file_type': file.type,
        'file_size': file.size,
      },
      success: (uploadRes: any) => {
        try {
          const result = JSON.parse(uploadRes.data)
          if (result.code === '200') {
            resolve(result.data.fileUrl)
          } else {
            reject(new Error(result.message || '文件上传失败'))
          }
        } catch (e) {
          reject(new Error('文件上传响应解析失败'))
        }
      },
      fail: (error: any) => {
        reject(error)
      }
    })

    // 监听上传进度
    if (onProgress) {
      uploadTask.onProgressUpdate((res: any) => {
        onProgress(res.progress)
      })
    }
  })
}

/**
 * 批量上传文件
 * @param url 上传URL
 * @param files 文件列表
 * @param parallel 是否并行上传，默认为false（顺序上传）
 * @param formData 额外的表单数据
 * @param onProgress 进度回调函数
 * @param onFileComplete 单个文件完成回调
 * @returns Promise<UploadedFile[]> 返回上传后的文件信息列表
 */
export const uploadAttachments = async (
  files: FileInfo[],
  parallel: boolean = false,
  formData: UploadFormData = {},
  onProgress?: (current: number, total: number) => void,
  onFileComplete?: (file: UploadedFile, index: number) => void
): Promise<UploadedFile[]> => {
  const uploadedFiles: UploadedFile[] = []

  const url = getApiUrl("/workflow/attachment")
  if (parallel) {
    // 并行上传
    const uploadPromises = files.map((file, index) => {
      return uploadFile({ url, file, formData })
        .then(fileUrl => {
          const uploadedFile = {
            path: file.path,
            size: file.size,
            type: file.type,
            url: fileUrl
          }

          if (onFileComplete) {
            onFileComplete(uploadedFile, index)
          }

          if (onProgress) {
            onProgress(index + 1, files.length)
          }

          return uploadedFile
        })
        .catch(error => {
          console.error(`文件 ${file.name} 上传失败:`, error)
          // 返回null表示上传失败，后续过滤掉
          return null
        })
    })

    const results = await Promise.all(uploadPromises)
    // 过滤掉上传失败的文件
    return results.filter(result => result !== null) as UploadedFile[]
  } else {
    // 顺序上传
    for (let i = 0; i < files.length; i++) {
      const file = files[i]
      try {
        const fileUrl = await uploadFile({ url, file, formData })

        const uploadedFile = {
          path: file.path,
          size: file.size,
          type: file.type,
          url: fileUrl
        }

        uploadedFiles.push(uploadedFile)

        if (onFileComplete) {
          onFileComplete(uploadedFile, i)
        }

        if (onProgress) {
          onProgress(i + 1, files.length)
        }
      } catch (error) {
        console.error(`文件 ${file.name} 上传失败:`, error)
        // 顺序上传时，一个文件失败不影响其他文件上传
      }
    }

    return uploadedFiles
  }
} 